Skip to main content

Good Coding Practice

#programming

  • DRY Principle
    • Don't repeat yourself and remove duplication wherever possible
  • SOLID Principles
    • Single responsibility principle
      • A class or module should do one thing only
      • This is important because we don't want multiple reasons for why the class or module should change
    • Open/closed principle
      • Open for extension
        • The class can be inherited or overwritten
      • Closed for modification
        • Should not have switch conditions inside that needs to be changed in order to work
    • Liskov substitution principle
      • Any child type of a parent type should be able to stand in for that parent without things blowing up
      • If you have an animal class with make_noise() method then any child classes of cats and dogs, they both should have proper implementations of make_noise() and not be throwing an exception
    • Interface segregation principle
      • Should favour many, smaller, client-specific interfaces over a single, larger, monolithic interface
      • If you have an interface with lots of configurations that you have to set up with default values then it is not a good practice
    • Dependency inversion principle
      • Write code that depends upon abstractions rather than concrete details
      • Classes that takes in generic variables instead of instantiating a specific value internally
  • Law of Demeter
    • An OOP rule that helps to write clean code
    • For all classes C, and for all methods M attached to C, all objects to which M sends a message must be:

    • M's argument objects, including the self object or
    • The instance variable objects of C
    • For all classes C, and for all methods M attached to C, all objects to which M sends a message must be:
      • self
      • M's argument objects
      • Instance variable objects of C
      • Objects created by M, or by functions or methods which M calls
      • Objects in global variables
    • This means that this law prohibits "sending a message" to any already existing object that is held in instance variables of other classes, unless it is also held by our class or passed to us as method parameters